package com.example.demo111111.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.demo111111.entity.User;
import com.example.demo111111.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            token = request.getParameter("token");
        }

        if(StrUtil.isBlank(token)){
            throw new Exception("登录状态异常，请重新登录");
        }

        String account;
        User user = null;
        try{
            account = JWT.decode(token).getAudience().get(0);
            user = userService.findUserByAccount(account);
        }catch (Exception e){
            log.error("无效tonken，token:" + token);
        }

        if(user == null){
            throw new Exception("用户不存在，请重新登录");
        }

        try{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            throw new Exception("token验证失败，请重新登录");
        }
        return true;
    }
}
